/**     
 * @Title: NettyEmbeddedContext.java   
 * @Package me.springboot.netty.context   
 * @Description: TODO
 * @author weiwei 
 * @date 2017年8月25日 下午2:02:46   
 * @version V1.0     
 */
package me.springboot.netty.context;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import io.netty.util.AsciiString;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;

import me.springboot.netty.dispatcher.NettyRequestDispatcher;
import me.springboot.netty.filer.NettyFilterRegistration;
import me.springboot.netty.filer.SimpleFilterChain;
import me.springboot.netty.servlet.NettyServletRegistration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.collect.ImmutableMap;

/**
 * @ClassName: NettyEmbeddedContext
 * @Description: TODO
 * @author weiwei
 * @date 2017年8月25日 下午2:02:46
 * 
 */
public class NettyEmbeddedContext implements ServletContext {

	private final Log logger = LogFactory.getLog(NettyEmbeddedContext.class);

	private final String contextPath;

	private final ClassLoader classLoader;

	private final Map<String, NettyServletRegistration> servlets = new HashMap<String, NettyServletRegistration>();

	private final Map<String, String> servletMappings = new HashMap<String, String>();

	private final Map<String, NettyFilterRegistration> filters = new HashMap<String, NettyFilterRegistration>();

	private final AsciiString serverInfo;

	private volatile boolean initialised;

	private int sessionTimeout;

	private String encoding;

	public NettyEmbeddedContext(String contextPath, ClassLoader classLoader, String serverInfo) {
		this.contextPath = contextPath;
		this.classLoader = classLoader;
		this.serverInfo = new AsciiString(serverInfo);
		this.sessionTimeout = 30;
		this.encoding = "UTF-8";
	}

	public NettyEmbeddedContext(String contextPath, ClassLoader classLoader, String serverInfo, int sessionTimeout, String encoding) {
		this.contextPath = contextPath;
		this.classLoader = classLoader;
		this.serverInfo = new AsciiString(serverInfo);
		this.sessionTimeout = sessionTimeout;
		this.encoding = encoding;
	}

	public void setInitialised(boolean initialised) {
		this.initialised = initialised;
	}

	public boolean isInitialised() {
		return initialised;
	}

	public void checkNotInitialised() {
		checkState(!isInitialised(), "This method may not be called after the context has been initialised");
	}

	public void addServletMapping(String urlPattern, String name) {
		checkNotInitialised();
		servletMappings.put(urlPattern, checkNotNull(name));
	}

	public void addFilterMapping(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String urlPattern) {
		checkNotInitialised();
		// TODO
	}

	@Override
	public ServletContext getContext(String uripath) {
		return null;
	}

	@Override
	public String getContextPath() {
		return contextPath;
	}

	@Override
	public int getMajorVersion() {
		return 0;
	}

	@Override
	public int getMinorVersion() {
		return 0;
	}

	@Override
	public int getEffectiveMajorVersion() {
		return 0;
	}

	@Override
	public int getEffectiveMinorVersion() {
		return 0;
	}

	@Override
	public String getMimeType(String file) {
		return null;
	}

	@Override
	public Set<String> getResourcePaths(String path) {
		return null;
	}

	@Override
	public URL getResource(String path) throws MalformedURLException {
		return null;
	}

	@Override
	public InputStream getResourceAsStream(String path) {
		return null;
	}

	@Override
	public RequestDispatcher getRequestDispatcher(String path) {
		// FIXME proper path matching
		String servletName = servletMappings.get(path);
		if (servletName == null) {
			servletName = servletMappings.get("/");
		}
		Servlet servlet = null;
		try {
			servlet = null == servletName ? null : servlets.get(servletName).getServlet();
			if (servlet == null) {
				return null;
			}
			// FIXME proper path matching
			List<Filter> filters = new ArrayList<Filter>();
			for (NettyFilterRegistration registration : this.filters.values()) {
				filters.add(registration.getFilter());
			}
			FilterChain filterChain = new SimpleFilterChain(servlet, filters);
			return new NettyRequestDispatcher(this, filterChain);
		} catch (ServletException e) {
			// TODO log exception
			return null;
		}
	}

	@Override
	public RequestDispatcher getNamedDispatcher(String name) {
		return null;
	}

	@Override
	public Servlet getServlet(String name) throws ServletException {
		return servlets.get(name).getServlet();
	}

	@Override
	public Enumeration<Servlet> getServlets() {
		return Collections.emptyEnumeration();
	}

	@Override
	public Enumeration<String> getServletNames() {
		return Collections.emptyEnumeration();
	}

	@Override
	public void log(String msg) {
		logger.info(msg);
	}

	@Override
	public void log(Exception exception, String msg) {
		logger.error(msg, exception);
	}

	@Override
	public void log(String message, Throwable throwable) {
		logger.error(message, throwable);
	}

	@Override
	public String getRealPath(String path) {
		return null;
	}

	@Override
	public String getServerInfo() {
		return serverInfo.toString();
	}

	public AsciiString getServerInfoAscii() {
		return serverInfo;
	}

	@Override
	public String getInitParameter(String name) {
		return null;
	}

	@Override
	public Enumeration<String> getInitParameterNames() {
		return Collections.emptyEnumeration();
	}

	@Override
	public boolean setInitParameter(String name, String value) {
		return false;
	}

	@Override
	public Object getAttribute(String name) {
		return null;
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		return Collections.emptyEnumeration();
	}

	@Override
	public void setAttribute(String name, Object object) {

	}

	@Override
	public void removeAttribute(String name) {

	}

	@Override
	public String getServletContextName() {
		return null;
	}

	@Override
	public ServletRegistration.Dynamic addServlet(String servletName, String className) {
		return addServlet(servletName, className, null);
	}

	@Override
	public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
		return addServlet(servletName, servlet.getClass().getName(), servlet);
	}

	@Override
	public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
		return addServlet(servletName, servletClass.getName());
	}

	private ServletRegistration.Dynamic addServlet(String servletName, String className, Servlet servlet) {
		NettyServletRegistration servletRegistration = new NettyServletRegistration(this, servletName, className, servlet);
		servlets.put(servletName, servletRegistration);
		return servletRegistration;
	}

	@Override
	public <T extends Servlet> T createServlet(Class<T> c) throws ServletException {
		return null;
	}

	@Override
	public ServletRegistration getServletRegistration(String servletName) {
		return null;
	}

	@Override
	public Map<String, ? extends ServletRegistration> getServletRegistrations() {
		return null;
	}

	@Override
	public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className) {
		return addFilter(filterName, className, null);
	}

	@Override
	public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
		return addFilter(filterName, filter.getClass().getName(), filter);
	}

	private javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className, Filter filter) {
		NettyFilterRegistration filterRegistration = new NettyFilterRegistration(this, filterName, className, filter);
		filters.put(filterName, filterRegistration);
		return filterRegistration;
	}

	@Override
	public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
		return addFilter(filterName, filterClass.getName());
	}

	@Override
	public <T extends Filter> T createFilter(Class<T> c) throws ServletException {
		return null;
	}

	@Override
	public javax.servlet.FilterRegistration getFilterRegistration(String filterName) {
		return filters.get(filterName);
	}

	@Override
	public Map<String, ? extends javax.servlet.FilterRegistration> getFilterRegistrations() {
		return ImmutableMap.copyOf(filters);
	}

	@Override
	public SessionCookieConfig getSessionCookieConfig() {
		return null;
	}

	@Override
	public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) throws IllegalStateException, IllegalArgumentException {

	}

	@Override
	public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
		return null;
	}

	@Override
	public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
		return null;
	}

	@Override
	public void addListener(String className) {

	}

	@Override
	public <T extends EventListener> void addListener(T t) {

	}

	@Override
	public void addListener(Class<? extends EventListener> listenerClass) {

	}

	@Override
	public <T extends EventListener> T createListener(Class<T> c) throws ServletException {
		return null;
	}

	@Override
	public void declareRoles(String... roleNames) {

	}

	@Override
	public String getVirtualServerName() {
		return null;
	}

	@Override
	public ClassLoader getClassLoader() {
		return classLoader;
	}

	@Override
	public JspConfigDescriptor getJspConfigDescriptor() {
		return null;
	}

	/*
	 * (非 Javadoc) <p>Title: addJspFile</p> <p>Description: </p>
	 * 
	 * @param servletName
	 * 
	 * @param jspFile
	 * 
	 * @return
	 * 
	 * @see javax.servlet.ServletContext#addJspFile(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Dynamic addJspFile(String servletName, String jspFile) {
		return null;
	}

	@Override
	public int getSessionTimeout() {
		return sessionTimeout;
	}

	@Override
	public void setSessionTimeout(int sessionTimeout) {
		this.sessionTimeout = sessionTimeout;
	}

	@Override
	public String getRequestCharacterEncoding() {
		return encoding;
	}

	@Override
	public void setRequestCharacterEncoding(String encoding) {
		this.encoding = encoding;
	}

	@Override
	public String getResponseCharacterEncoding() {
		return encoding;
	}

	@Override
	public void setResponseCharacterEncoding(String encoding) {
		this.encoding = encoding;
	}
}
